import json

from django.contrib.auth.hashers import make_password
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Prefetch
from django.shortcuts import render

from accounts.views import is_captcha_valid
from apps.accounts.models import CustomUser
from apps.rootone.models import Class, CourseClassZj, ExaLocationZj, Other_teacher_class, Course
from apps.teacherapp.models import Teacher, Leave_zong, set_Grades_course
from .models import SStudents, S_user, student_award_zj, S_award, mb_setting
# Create your views here.
from django.http import JsonResponse

# 下面两个是处理用户验证的导入
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes

#处理登录请求的导入
from rest_framework.response import Response
from rest_framework import status


# 验证码
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
import json
# 查询学生全部数据
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def all_student_if(request):
    try:
        student_id = request.query_params.get('student_id')  # 获取学号参数
        if not student_id:
            return Response({'message': '学号为空！'}, status=status.HTTP_400_BAD_REQUEST)  # 更正状态码为 400

        # 使用 filter 来查找学生数据，如果没有找到会返回空的查询集
        user = SStudents.objects.filter(student_id=student_id).first()

        if not user:
            return Response({'message': '未找到该学号的学生信息！'}, status=status.HTTP_404_NOT_FOUND)

        # 将模型实例转换为字典并只保留模型字段数据
        user_all_data = {k: v for k, v in user.__dict__.items() if not k.startswith('_')}

        # 处理 of_class_id 并获取对应的班级名称
        of_class_id = getattr(user, 'of_class_id', None)
        class_object = None
        if of_class_id:
            class_object = Class.objects.filter(class_id=of_class_id).first()
            if class_object:
                user_all_data['class_name'] = class_object.class_name
            else:
                user_all_data['class_name'] = '班级信息不存在'
        else:
            user_all_data['class_name'] = '无班级信息'
        print(user_all_data)
        # 返回学生信息
        return JsonResponse({'code': 1, 'data': user_all_data}, status=status.HTTP_200_OK)

    except Exception as e:
        print(f'解析学生信息错误, 原因是:{e}')
        return Response({'message': '服务器错误'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)






# @api_view(['POST'])
# def login(request):
#         # 获取请求数据
#         username = request.data.get('username')
#         password = request.data.get('password')
#
#         if not username or not password:
#             return JsonResponse({'message': '用户名或密码不能为空!'}, status=status.HTTP_400_BAD_REQUEST)
#
#         try:
#             # 获取对应学号的学生信息
#             user = S_user.objects.get(sstudent__student_id=username)  # 使用 sstudent__student_id 查询
#             if user.password == password:
#                 return JsonResponse({'message': '登录成功'}, status=status.HTTP_200_OK)
#             else:
#                 return JsonResponse({'message': '用户名或密码错误!'}, status=status.HTTP_401_UNAUTHORIZED)
#         except S_user.DoesNotExist:
#             return JsonResponse({'message': '用户名或密码错误!'}, status=status.HTTP_401_UNAUTHORIZED)
#         except Exception as e:
#             return JsonResponse({'message': f'错误信息：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
#


@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def head_name(request):
    try:
        # 获取请求参数
        student_id = request.query_params.get('student_id')
        if not student_id:
            return Response({'message': '学号不能为空！'}, status=status.HTTP_400_BAD_REQUEST)
        # 查询用户信息
        try:
            user_name = SStudents.objects.get(student_id=student_id)
            really_name = user_name.rname
            return Response({'name': really_name}, status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response({'message': '学号不存在！'}, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        # 捕获其他未知错误
        return Response({'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 查看奖状
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def view_award(request):
    try:
        student_id = request.query_params.get('student_id')
        if not student_id:
            return Response({'message': '学号不能为空！'}, status=status.HTTP_400_BAD_REQUEST)
        student = SStudents.objects.get(student_id=student_id)
        awards = student_award_zj.objects.filter(student_name=student).select_related('student_award', 'com_teacher_name')
        if not awards.exists():
            return Response({'message': '该学生没有奖项数据！'}, status=status.HTTP_404_NOT_FOUND)
        # 创建一个字典来缓存教师ID和名字的映射，避免重复查询
        teacher_cache = {teacher.sid: teacher.rname for teacher in Teacher.objects.all()}
        awards_data = []
        processed_awards = set()  # 用于跟踪已经处理过的奖项，避免重复
        for award in awards:
            award_id = award.student_award.award_id
            if award_id in processed_awards:
                continue  # 如果这个奖项已经处理过，则跳过
            # 获取当前奖的指导教师合集，并提取名字
            related_awards = student_award_zj.objects.filter(
                student_name=student,
                student_award__award_id=award_id
            ).select_related('com_teacher_name')
            # 字典的 get 方法用于根据键（key）获取对应的值。使用 get 方法时，你只需要传递键本身作为参数，不需要用引号包裹键，除非该键是一个字符串
            teacher_names = [
                teacher_cache.get(teacher_obj.com_teacher_name.sid, '未知')  # 使用缓存的名字
                for teacher_obj in related_awards
            ]
            awards_data.append({
                'award_id': award_id,
                'award_name': award.student_award.award_name,
                'award_unit': award.student_award.award_unit,
                'award_time': award.student_award.award_time.strftime('%Y-%m-%d'),  # 格式化日期
                'award_text': award.student_award.award_text,
                'award_teachers': ', '.join(teacher_names),  # 使用逗号连接教师名字
            })

        return Response({'code': 1, 'message': awards_data}, status=status.HTTP_200_OK)
    except Exception as e:
        print(f"Error: {str(e)}")
        return Response({'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 修改个人信息
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def person_update(request):
    try:
        # 获取前端传来的数据
        student_id = request.data.get('studentid')
        rname_q = request.data.get('username')
        sex_q = request.data.get('sex')
        birthday_q = request.data.get('birthday')
        phone_q = request.data.get('phone')
        email_q = request.data.get('email')
        orgin_q = request.data.get('orgin')

        # 查找学生信息
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息，请联系管理员'}, status=status.HTTP_404_NOT_FOUND)

        # 更新学生信息
        try:
            user.rname = rname_q
            user.sex = sex_q
            user.birthday = birthday_q
            user.phone = phone_q
            user.mailbox = email_q
            user.origin = orgin_q
            user.save()

            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 修改其他信息
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def other_update(request):
    try:
        # 获取前端传来的数据
        student_id = request.data.get('studentid')
        by_school_q = request.data.get('by_school')
        school_encode_q = request.data.get('school_encode')
        hire_q = request.data.get('hire')
        college_q = request.data.get('college')
        of_class_q = request.data.get('of_class')

        # 查找学生信息
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息，请联系管理员'}, status=status.HTTP_404_NOT_FOUND)

        # 新增实例化班级
        try:

            class_object = Class.objects.filter(class_name=of_class_q.strip()).first()
        except Class.DoesNotExist:
            return Response({'code': 2, 'message': '此班级不存在'}, status=status.HTTP_400_BAD_REQUEST)

        # 更新学生信息
        try:
            user.by_school = by_school_q
            user.school_encode = school_encode_q
            user.hire = hire_q
            user.college = college_q
            user.of_class = class_object

            user.save()

            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 修改家庭信息
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def family_update(request):
    try:
        # 获取前端传来的数据
        student_id = request.data.get('studentid')
        f_name_q = request.data.get('f_name')
        f_phone_q = request.data.get('f_phone')
        m_name_q = request.data.get('m_name')
        m_phone_q = request.data.get('m_phone')
        address_q = request.data.get('address')


        # 查找学生信息
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息，请联系管理员'}, status=status.HTTP_404_NOT_FOUND)

        # 更新学生信息
        try:
            user.f_name = f_name_q
            user.f_phone = f_phone_q
            user.m_name = m_name_q
            user.m_phone = m_phone_q
            user.address = address_q
            user.save()

            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 改密码
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def password_update(request):
    try:
        # 获取前端传来的数据
        student_id = request.data.get('studentid')
        password_q = request.data.get('newPassword')

        # 查找学生信息
        try:
            user = CustomUser.objects.get(identifier=student_id)
        except CustomUser.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的信息，请联系管理员'}, status=status.HTTP_404_NOT_FOUND)

            # 更新个人密码并进行哈希处理
        try:
            # 哈希处理~make_password
            user.password = make_password(password_q)  # 使用 Django 的 make_password 函数
            user.save()
            return Response({'code': 1, 'message': '修改成功！'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'修改失败：{str(e)}'}, status=status.HTTP_400_BAD_REQUEST)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def mb_update(request):
    """
    更新或创建密保信息接口
    """
    try:
        # 获取请求中的数据
        student_id = request.data.get('studentid')
        mb_name1 = request.data.get('securityQuestion1')
        mb_answer1 = request.data.get('answer1')
        mb_name2 = request.data.get('securityQuestion2')
        mb_answer2 = request.data.get('answer2')
        mb_name3 = request.data.get('securityQuestion3')
        mb_answer3 = request.data.get('answer3')

        # 校验 student_id 是否为空
        if not student_id:
            return Response({'code': 2, 'message': '学号不能为空！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            # 获取关联的学生实例
            student_instance = S_user.objects.get(sstudent__student_id=student_id)
        except S_user.DoesNotExist:
            return Response({'code': 2, 'message': '学生信息不存在！'}, status=status.HTTP_404_NOT_FOUND)

        # 获取或创建密保信息
        user, created = mb_setting.objects.get_or_create(
            # !!!!在 Django 中，外键字段只能与相关的实例对象进行比较，而不能直接与实例对象的主键（ID）进行比较。
            sstudents=student_instance,
            defaults={
                'sstudents_id': student_instance.id,
                'mb_name1': mb_name1,
                'mb_answer1': mb_answer1,
                'mb_name2': mb_name2,
                'mb_answer2': mb_answer2,
                'mb_name3': mb_name3,
                'mb_answer3': mb_answer3,
            }
        )

        # 如果记录已存在，更新密保信息
        if not created:
            user.mb_name1 = mb_name1
            user.mb_answer1 = mb_answer1
            user.mb_name2 = mb_name2
            user.mb_answer2 = mb_answer2
            user.mb_name3 = mb_name3
            user.mb_answer3 = mb_answer3
            user.save()

        return Response({'code': 1, 'message': '密保信息更新成功！'}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
# @permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def load_mb(request):
    try:
        # 获取学生 ID
        student_id = request.data.get('studentid')
        if not student_id:
            return Response({'code': 2, 'message': '需要查询密保信息的学号为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 查询 SStudents 表获取学生信息
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': f'搜索不到学生id {student_id}'}, status=status.HTTP_404_NOT_FOUND)

        # 查询 S_user 表获取学生账号信息
        try:
            user_account = S_user.objects.get(sstudent=user)
        except S_user.DoesNotExist:
            return Response({'code': 2, 'message': f'未找到学生账号信息 (student_id: {student_id})'}, status=status.HTTP_404_NOT_FOUND)

        # 查询 mb_setting 表获取密保信息
        try:
            mb_message = mb_setting.objects.filter(sstudents=user_account).values(
                'mb_name1', 'mb_answer1',
                'mb_name2', 'mb_answer2',
                'mb_name3', 'mb_answer3'
            )
            if not mb_message.exists():
                return Response({'code': 2, 'message': '您还未设置密保信息，请尽快设置'},
                                status=status.HTTP_404_NOT_FOUND)

            # 返回查询结果
            return JsonResponse({'code': 1, 'data': list(mb_message)}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'查询密保信息失败：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 忘记密码——密保校验
@api_view(['POST'])
# @permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def pwd_fg(request):
    try:
        student_id = request.data.get('username')
        captcha_key = request.data.get('captcha_key')
        captcha_value = request.data.get('captcha_value')

        if not captcha_key or not captcha_value:
            return Response({'message': '请输入验证码'}, status=status.HTTP_400_BAD_REQUEST)

            # 验证验证码
        if not is_captcha_valid(captcha_key, captcha_value):
            return Response({'message': '验证码错误'}, status=status.HTTP_400_BAD_REQUEST)



        if not student_id:
            return Response({'code': 2, 'message': '学号为空！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': f'搜索不到学生id {student_id}'}, status=status.HTTP_404_NOT_FOUND)
        # user_id = S_user.objects.get(sstudent=user)
        try:
            user_mb = mb_setting.objects.filter(sstudents=user).values(
                'mb_name1',
                'mb_name2',
                'mb_name3'
            )
            print(list(user_mb))
            return JsonResponse({'code': 1, 'data': list(user_mb)}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'code': 2, 'message': f'查询密保信息失败：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


    except Exception as e:
        return Response({'code': 2, 'message':f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
# @permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def verify_mb(request):
    try:
        student_id = request.data.get('username')
        security_answers = request.data.get('securityAnswers')  # 获取密保答案对象


        if not student_id:
            return Response({'code': 2, 'message': '学号为空！'}, status=status.HTTP_400_BAD_REQUEST)

        if not security_answers or len(security_answers) != 3:
            return Response({'code': 2, 'message': '密保答案不完整！'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': f'搜索不到学生id {student_id}'}, status=status.HTTP_404_NOT_FOUND)


        try:
            user_mb = mb_setting.objects.get(sstudents=user)

            # 从数据库中获取用户的密保答案
            db_answer1 = user_mb.mb_answer1
            db_answer2 = user_mb.mb_answer2
            db_answer3 = user_mb.mb_answer3

            # 比较用户提供的答案与数据库中的密保答案
            if security_answers.get('question1') != db_answer1 or \
                    security_answers.get('question2') != db_answer2 or \
                    security_answers.get('question3') != db_answer3:
                return Response({'code': 2, 'message': '密保答案错误'}, status=status.HTTP_400_BAD_REQUEST)

            return Response({'code': 1, 'message': '校对密保答案成功, 请更新您的密码'}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'code': 2, 'message': f'校对密保答案失败：{str(e)}'},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 返回一个班级的辅导员姓名
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def student_view_fdy(request):
    try:
        student_id = request.data.get('username')
        if not student_id:
            return Response({'code': 2, 'message': '学号为空！'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': f'搜索不到学生id {student_id}'}, status=status.HTTP_404_NOT_FOUND)
        try:
            # 得到学生的班级id
            class_id_x = user.of_class.class_id
            # 实例化对应学生班级id的对象
            class_object = Class.objects.get(class_id=class_id_x)
            # 搜索与实例化对象的辅导员id匹配的教师
            teacher = Teacher.objects.get(sid=class_object.fdy_id)
            fdy_rname = teacher.rname
            return JsonResponse({'code': 1, 'data': fdy_rname}, status=status.HTTP_200_OK)
        except Exception as f:
            return Response({'code': 2, 'message': f'错误原因：{str(f)}'}, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# 获取我的请假记录
@api_view(['POST'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def my_leave_record(request):
    try:
        student_id_q = request.data.get('studentid')
        if not student_id_q:
            return Response({'code': 2, 'message': '学号为空！'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = SStudents.objects.get(student_id=student_id_q)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到您的学号信息，请稍后再试。'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            my_leaves = Leave_zong.objects.filter(student_id=student_id_q)
            my_leave = [
                {
                    'student_id': i.student_id,
                    'student_rname': i.student_rname,
                    'student_class': i.student_class,
                    'start_time': i.start_time.strftime('%Y-%m-%d %H:%M'),  # 格式化时间
                    'stop_time': i.stop_time.strftime('%Y-%m-%d %H:%M'),  # 格式化时间
                    'leave_cause': i.leave_cause,
                    'approver_person': i.approver_person.rname if i.approver_person else None,  # 返回审批人姓名
                    'approver_opinion': i.approver_opinion,
                    'approver_out': i.approver_out,
                    'approver_time': i.approver_time.strftime('%Y-%m-%d %H:%M') if i.approver_time else None,  # 格式化时间
                }
                for i in my_leaves
            ]

            return JsonResponse({"code": 1, "message": "获取成功", "data": my_leave}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'code': 2, 'message': f'错误原因：{str(e)}'}, status=status.HTTP_404_NOT_FOUND)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)






# 学生查看本班级考的科目信息
@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def s_get_all_the_exa(request):
    student_id = request.query_params.get('studentid')

    if not student_id:
        return Response({'code': 2, 'message': '学号不能为空'}, status=status.HTTP_400_BAD_REQUEST)

    try:
        # 获取学生对象并检查是否存在
        student_object = SStudents.objects.select_related('of_class').get(student_id=student_id)
    except SStudents.DoesNotExist:
        return Response({'code': 2, 'message': '未能找到该学号'}, status=status.HTTP_404_NOT_FOUND)

    try:
        # 获取班级对象并检查是否存在
        class_object = student_object.of_class
    except AttributeError:
        return Response({'code': 2, 'message': '未能找到此班级'}, status=status.HTTP_404_NOT_FOUND)

    try:

        # 高难，需要后期深透化理解
        # 使用Prefetch预加载教师信息，避免N+1查询问题
        ks_objects = ExaLocationZj.objects.filter(cclass=class_object).prefetch_related(
            Prefetch('course__courseclasszj_set', queryset=CourseClassZj.objects.select_related('teacher'))
        )

        ks_objects_data = [
            {
                'course_id': i.course.course_id,
                'course_name': i.course.name,
                'start_time': i.start_at.isoformat() if i.start_at else None,
                'end_time': i.end_at.isoformat() if i.end_at else None,
                'location': i.location.name if i.location else '',
                'teacher': get_teacher_name(i.course, class_object) if i.course else '未知'
            }
            for i in ks_objects
        ]

        return Response({'code': 1, 'data': ks_objects_data}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 辅助方法，获取考试科目的授课老师
def get_teacher_name(course, class_object):
    """Helper function to safely get the teacher's name."""
    try:
        course_class_zj = CourseClassZj.objects.filter(course=course, cclass=class_object).first()
        if course_class_zj and course_class_zj.teacher:

            return course_class_zj.teacher.rname
    except AttributeError:
        pass
    return '未知'





# 学生查看自己的考试成绩

@api_view(['GET'])
@permission_classes([IsAuthenticated])  # 确保只有经过认证的用户可以访问
def student_view_my_gra(request):
    try:
        student_id = request.query_params.get('studentid')
        year_q = request.query_params.get('year')
        qua_q = request.query_params.get('qua')
        if not student_id:
            return Response({'code': 2, 'message': '学号或班级编号不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证学生、班级和课程的存在性
        try:
            student_object = SStudents.objects.get(student_id=student_id)
        except SStudents.DoesNotExist:
            return Response({'code': 2, 'message': '未能找到该学生编号'}, status=status.HTTP_404_NOT_FOUND)


        # 返回指定学号下的所有课程成绩信息
        student_objects = set_Grades_course.objects.filter(student=student_object,
                                                           year=str(year_q),
                                                           qua=int(qua_q))
        students_data = [
            {
                "course_id": student.course.course_id,
                "course_name": student.course.name,
                "usual_score": student.ps_gr,
                "exam_score": student.ks_gr,
                "total_score": student.z_gr
            }
            for student in student_objects
        ]
        print(students_data)
        return Response({'code': 1, 'data': students_data}, status=status.HTTP_200_OK)

    except Exception as e:
        return Response({'code': 2, 'message': f'服务器错误: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
